package integral

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/app/business/api/internal/repository/integral"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizintegral"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralorder"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type IntegralGoodsOrderListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 积分商城订单列表
func NewIntegralGoodsOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralGoodsOrderListLogic {
	return &IntegralGoodsOrderListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *IntegralGoodsOrderListLogic) IntegralGoodsOrderList(req *types.IntegralGoodsOrderListRequest) (resp *types.IntegralGoodsOrderListResponse, err error) {
	// 定义百分之一初始值
	baiDecimal := decimal.NewFromInt32(100)
	// 获取当前时间
	now := time.Now()
	//获取用户信息
	userId := common.JwtAuthUserId(l.ctx)
	integralOrderDao := integral.NewIntegralOrderDao(l.ctx, l.svcCtx)

	//构建积分商品订单查询条件
	integralOrderConditions := make([]predicate.HzIntegralOrder, 0)
	integralOrderConditions = append(integralOrderConditions, hzintegralorder.OrderUserIDEQ(userId))
	switch req.Type {
	case bizintegral.RecentDays:
		// 计算最近30天的开始时间（从当前时间往前推30天）
		startOf30Days := common.GetRecentThirtyDays(now)
		// 最近30天的结束时间就是当前时间
		endOf30Days := now
		integralOrderConditions = append(integralOrderConditions, hzintegralorder.CreatedAtGTE(startOf30Days.Unix()), hzintegralorder.CreatedAtLTE(endOf30Days.Unix()))
	case bizintegral.AlreadyReceived:
		integralOrderConditions = append(integralOrderConditions, hzintegralorder.OrderStatusEQ(bizintegral.Received))
	case bizintegral.NotReceived:
		integralOrderConditions = append(integralOrderConditions, hzintegralorder.OrderStatusEQ(bizintegral.UnReceived))
	}

	//查询列表
	orders, total, err := integralOrderDao.IntegralOrderByConditionPages(integralOrderConditions, req.Current, req.PageSize)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询商品订单列表失败：%s", err.Error()))
	}
	
	//组装返回数据
	list := lo.Map(orders, func(item *ent.HzIntegralOrder, _ int) *types.IntegralGoodsOrder {
		return &types.IntegralGoodsOrder{
			Id:               int64(item.ID),
			OrderNo:          item.OrderNo,
			GoodsInfo:        item.OrderGoodsInfo,
			GoodsImage:       fmt.Sprintf("%s%s", constant.IntegralGoodsImage, item.OrderGoodsImage),
			GoodsNum:         item.OrderGoodsNumber,
			GoodsAmount:      decimal.NewFromInt(item.OrderGoodsAmount).Div(baiDecimal).StringFixed(2),
			OrderGoodsSecret: item.OrderGoodsSecret,
			OrderStatus:      item.OrderStatus,
			CreatedAt:        item.CreatedAt,
		}
	})

	//组装返回数据
	resp = &types.IntegralGoodsOrderListResponse{
		Page: &types.PageResponse{
			Current:         req.Current,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Total:           int64(total),
		},
		List: list,
	}

	return resp, nil
}
